package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojo.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2022/1/12 9:53
 *  拦截器
 *
 */
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("userId");
        Optional<String> optional = Optional.ofNullable(userId);
        // 改方法如果存在值
        if (optional.isPresent()){
            // 把用户id存入ThreadLocal中
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtil.setUser(wmUser);
            log.info("WmTokenInterceptor设置用户信息到threadLocal中。。。");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        log.info("清理threadLocal");
        WmThreadLocalUtil.clear();
    }
}
